/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
export default class IotConstants {
  static readonly IOT_TAG = 'IOT_LOG';
  static readonly IOT_NAME = 'IOT';
  static readonly RETRY_COUNT = 3;
  static readonly SCAN_DURATION = 20 * 1000;
  static readonly CONNECT_TIMERS = 20 * 1000;
  static readonly RESPONSE_TIMERS = 20 * 1000;
  static readonly IOT_NOT_INIT = 1000;
  static readonly IOT_DISCOVERY_ERROR = 1001;
  static readonly IOT_CONNECT_ERROR = 1002;
  static readonly IOT_CONTROL_ERROR = 1003;
  static readonly IOT_CONTROL_COMMEND_ERROR = 1004;
  static readonly IOT_CALL_TIME_OUT = 1010;
  static readonly IOT_CONNECT_ERROR_MSG = 'iot-kit not connect';
  static readonly IOT_CALL_TIME_OUT_MSG = 'iot-kit time out';
  static readonly IOT_PARAMS_ERROR_MSG = 'parameter verification failed';
  static readonly ON_CONNECT_STATE_CHANGED: string = 'onConnectStateChanged';
  static readonly ON_DEVICE_DATA_CHANGED: string = 'onDeviceDataChanged';
  static readonly ON_CONNECT_STATE_CHANGED_TYPE: string = 'newStatus';
  static readonly SID_ALL_SERVICES: string = 'allservices';
  static readonly CUSTOM_SEC_DATA: string = 'customSecData';
}

export enum ConnectType {
  OFFLINE = 0, // 离线
  ONLINE = 1, // 在线
  CONNECTING = 2, // 连接中
}

/**
 * 设备状态
 */
export interface InfDeviceState {
  data: Record<string, string | number>
  sid: string,
}

export interface ServicesResponse {
  seq: number,
  services: InfDeviceState[],
  vendor: InfDeviceState[],
}

function hasProperty(key: string, obj: Object) {
  let keys = Object.keys(obj);
  for (let i = 0; i < keys.length; i++) {
    if (key == keys[i]) {
      return true;
    }
  }
  return false;
}

export function analysisPayload(payloadStr: string) {
  let messageResponse = JSON.parse(payloadStr) as ServicesResponse;
  let isVendor = hasProperty('vendor', messageResponse);
  let responseArray = isVendor ? messageResponse?.vendor : messageResponse?.services;
  return responseArray;
}
